package com.jjb.spider.mqtt.service;

import com.alibaba.fastjson.JSONObject;
import com.jjb.spider.mqtt.model.RetainMessage;
import com.jjb.spider.mqtt.model.WillMeaasge;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.mqtt.*;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ReactiveStringRedisTemplate;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

@Service
public class WillService {

    @Autowired
    private ReactiveStringRedisTemplate reactiveStringRedisTemplate;

    @Autowired
    private IMqttMessageService mqttMessageService;

    public Mono<Void> loginSuccess(String deviceId, ChannelHandlerContext ctx, MqttConnectMessage mqttMessage) {
        MqttConnectVariableHeader mqttConnectVariableHeader = mqttMessage.variableHeader();
        final MqttConnectPayload payload = mqttMessage.payload();

        Mono<Integer> mono = Mono.just(1);
        if( mqttConnectVariableHeader.isCleanSession() ) {
            //清除以前的记录
            mono = mono.flatMap(i ->
                 reactiveStringRedisTemplate.delete(deviceId).map(bool -> 1)
            );
        }

        if(mqttConnectVariableHeader.isWillFlag()) {
            //存在遗嘱消息
            int willQos = mqttConnectVariableHeader.willQos();
            String topic = payload.willTopic();
            boolean isWillRetain = mqttConnectVariableHeader.isWillRetain();
            byte[] willMessage = payload.willMessageInBytes();

            //保存遗嘱消息至redis
            WillMeaasge willMeaasge = new WillMeaasge(willQos, topic, isWillRetain, willMessage);
            mono =  mono.flatMap(i ->
                 reactiveStringRedisTemplate.opsForValue().set(deviceId+"_will_msg", JSONObject.toJSONString(willMeaasge))
                         .map(bool -> 1)
            );
        }

        return mono.flatMap(i -> Mono.empty());
    }


    public void willHandler(String deviceId) {
        //发送遗言消息
        this.reactiveStringRedisTemplate.opsForValue().get(deviceId+ "_will_msg")
                .flatMap(option -> {
                    if(!Strings.isNotBlank(option) ) {
                        return Mono.empty();
                    } else {
                        WillMeaasge willMeaasge = JSONObject.parseObject(option , WillMeaasge.class);
                        this.mqttMessageService.publish(willMeaasge);
                        //this.mqttMessageService.publish(willMeaasge.getTopic(), qos, willMeaasge.getWillQos(), willMeaasge.isWillRetain(), retainMessage);
                        return Mono.empty();
                    }
                }).subscribe();
    }
}
